{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b45a297c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "505ac8fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_size = 256\n",
    "train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4083dda9",
   "metadata": {},
   "outputs": [],
   "source": [
    "net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75e344ee",
   "metadata": {},
   "outputs": [],
   "source": [
    "def init_weights(m):\n",
    "    if type(m) == nn.Linear:\n",
    "        nn.init.normal_(m.weight, std=0.01)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "966204fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "net.apply(init_weights)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb580696",
   "metadata": {},
   "outputs": [],
   "source": [
    "loss = nn.CrossEntropyLoss() # 交叉熵损失函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c8314061",
   "metadata": {},
   "outputs": [],
   "source": [
    "trainer = torch.optim.SGD(net.parameters(), lr=0.1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bcbb0479",
   "metadata": {},
   "outputs": [],
   "source": [
    "num_epochs = 10\n",
    "d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "d2l",
   "language": "python",
   "name": "d2l"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
